package com.liu.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LIU
 * @version 1.0
 * @description TODO
 * @date 2024/2/20 10:09
 * lock接口 java concurrent包实现
 */
public class SaleTicketLock {

    public static void main(String[] args) {
        // 创建多个线程，调用资源类
        new Thread(new MyTask(), "AA").start();

        new Thread(new MyTask(), "BB").start();

        new Thread(new MyTask(), "CC").start();
    }
}

class MyTask implements Runnable {
    // ticket 对象 共享资源
    static Ticket ticket = new Ticket();

    @Override
    public void run() {
        for (int i = 0; i < 40; i++) {
            ticket.sale();
        }
    }
}

class Ticket {

    private int number = 30;
    // 可重入锁   fair公平锁
    private final Lock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (number > 0){
                System.out.println(Thread.currentThread().getName() + " ：卖出：" + number--);

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            lock.unlock();
        }
    }
}
